﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Org.Alexander.Edas
{
    class ConnectorPool
    {
        static ConnectorPool Ins = new ConnectorPool();
        private ConnectorPool() { }
        public static ConnectorPool GetIns()
        {
            return Ins;
        }

        private List<Connector> Pool;

        private SortedList<int,int> UsedPool;

        public void Init(int Capital,int BufferSize,Acceptor act)
        {
            Pool = new List<Connector>(Capital);
            UsedPool = new SortedList<int, int>(Capital);
            for (int i = 1; i < Capital+1 ; i++)
            {
                Connector con = new Connector(BufferSize, i);
                con.OnClose += new ConnectorMassageHandler(act.con_OnClose);
                con.OnInited += new ConnectorOperateHanlder(act.con_OnInited);
                con.OnRead += new ConnectorDataHandler(act.con_OnRead);
                con.OnSend += new ConnectorOperateHanlder(act.con_OnSend);
                con.OnError += new SocketErrorHandler(act.con_OnError);
                Pool.Add(con);
                UsedPool.Add(i, 0);
            }
            
        }

        public Connector this[int ID]
        {
            get
            {
                return Pool[ID - 1];
            }
        }

        public Connector GetFreeConnector()
        {
            int ID = 0;
            foreach (int k in UsedPool.Keys)
            {
                if (UsedPool[k] < 1)
                {
                    ID = k;
                    UsedPool[k] = 1;
                    return Pool[ID - 1];
                }
            }
            throw new Exception("Pool full!");
        }

        public void ReleaseConnector(int ID)
        {
            UsedPool[ID] = 0;
            //Pool[ID - 1].Retrieve();
        }

    }
}
